package com.example.smart.utils;

import android.content.Context;
import com.example.lib.utils.thread.ThreadPool;
import com.example.smart.listener.CopyVideoListener;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class FileUtils {

    //当前版本obb文件是否存在
    private static boolean obbIsExists(Context context, String name) {
        File obbFile = new File(context.getObbDir().getAbsolutePath(), name);
        return obbFile.exists();
    }

    //保存Obb包到本地文件
    public static void copyVideo(Context context, String name, CopyVideoListener listener) {
        ThreadPool.getInstance().execute(() -> {
            if (obbIsExists(context, name)) {
                listener.onSuccess(context.getExternalFilesDir("").getAbsoluteFile() + "/video/" + name);
            } else {
                try {

                    File file = new File(context.getExternalFilesDir("").getAbsoluteFile(), "/video");
                    if (!file.exists()) {
                        if (!file.mkdirs()) {
                            return;
                        }
                    }
                    File recodeFile = new File(file, name);
                    if (!recodeFile.exists()) {
                        if (!recodeFile.createNewFile()) {
                            return;
                        }
                    }
                    InputStream stream = context.getAssets().open(name);
                    FileOutputStream fos = new FileOutputStream(recodeFile);
                    byte[] buffer = new byte[1024];
                    int byteCount;
                    while ((byteCount = stream.read(buffer)) != -1) {
                        fos.write(buffer, 0, byteCount);
                    }
                    fos.flush();
                    stream.close();
                    fos.close();
                    listener.onSuccess(recodeFile.getAbsolutePath());
                } catch (RuntimeException | IOException e) {
                    e.printStackTrace();
                    listener.onFail();
                }
            }
        });
    }
}
